﻿using Newtonsoft.Json;
using Surf.GrpcInvoker.Demo.Core;
using System;
using System.Collections.Generic;
using System.Text;

namespace Surf.GrpcInvoker.Demo.Demo
{
    public class UserServiceGrpc
    {
        private static string __ServiceName = "UserService";
        private static string __MethodName = "GetUser";
        private static Marshaller<UserRequest> request = new Marshaller<UserRequest>(i => Serialize(i), b => Deserialize<UserRequest>(b));
        private static Marshaller<User> response = new Marshaller<User>(e => Serialize(e), b => Deserialize<User>(b));


        private static byte[] Serialize(object obj)
        {
            var data = JsonConvert.SerializeObject(obj);
            return Encoding.ASCII.GetBytes(data);
        }

        private static T Deserialize<T>(byte[] bytes)
        {
            var data = Encoding.ASCII.GetString(bytes);
            return JsonConvert.DeserializeObject<T>(data);
        }

        static readonly Method<UserRequest, User> _Method_GetUser = new Method<UserRequest, User>(__ServiceName, __MethodName, request, response);

        public static ServerServiceDefinition BindService(UserService userService)
        {
            return ServerServiceDefinition.CreateBuilder()
                .AddMethod(_Method_GetUser, userService.GetUser)
                .Build();
        }
    }
}
